<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Authentication Class
 *
 * Built on Mathew Davies' ReduxAuth
 * @copyright	Copyright (c) 1 June 2008, Mathew Davies
 * @see			http://code.google.com/p/reduxauth/
 * @license		http://www.opensource.org/licenses/mit-license.php The MIT License
 */

class Access
{
	var $CI;
	
	/**
	 * Constructor
	 *
	 * Loads the configuration options and assigns them to
	 * class variables available throughout the library.
	 *
	 * @access	public
	 * @param	void
	 * @return	void
	 */
	
	private $perms = array();
	function Access()
	{
		$this->CI =& get_instance();
		
		$auth = $this->CI->config->item('auth');
		//var_dump($auth);
		/* Config Variables */
		foreach($auth as $key => $value)
		{
			$this->$key = $value;
		}
		/*
		 * Edited By ManhVT to support moduler
		*/		
		//$this->CI->load->model('users_model');
		$this->CI->load->module_model('member', 'users_model', 'users_model');
		$this->users_model =& $this->CI->users_model;		
	}
	
	
	/**
	 * Register
	 *
	 * Registers a user
	 *
	 * @access	public
	 * @param	mixed userdata
	 * @return	mixed
	 */
	
	function register ($userdata)
	{
		/* Hash Password */
		$hash = sha1(microtime());
		$userdata['hash'] = $hash;
		$userdata['password'] = sha1($this->salt . $hash . $userdata['password']);

		/* Assign to default group */
		$userdata['type'] = $this->default_group;

		/* Check if email activation is enabled */
		if (!$this->email_activation)
		{
			$this->users_model->add_user($userdata);
			$this->login($userdata['username'], $userdata['password']);			
			return 'REGISTRATION_SUCCESS';
		}
		else
		{
			$CI =& get_instance();	
			$CI->load->library('email');
			$CI->email->initialize($this->mail);
			
			$key = sha1(microtime());

			$userdata['activation_code'] = $key;
			$this->users_model->add_user($userdata);
						
			$data['msg_view']	= 'activate';
			$data['link']		= anchor('member/activate/'.$key);
			
			$message = $CI->load->view('email/template', $data, TRUE);

			$CI->email->from($this->mail_from_email, $this->mail_from_name);
			$CI->email->to($userdata['email']);
			$CI->email->subject($this->email_activation_subject);
			$CI->email->message($message);
			$CI->email->send();
			
			return 'REGISTRATION_SUCCESS_EMAIL';
		}		

		return FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Login
	 *
	 * Verifies a user based on username and password
	 *
	 * @access	public
	 * @param	string username, password
	 * @return	bool
	 */
	function login($username, $password)
	{  
		$result = $this->users_model->get_login_info($username);
		//var_dump($result);
		if ($result) // Result Found
		{			
			if (empty($result->active))
			{
				return 'BANNED';
			}
			
			if (!empty($result->activation_code))
			{
				return 'NOT_ACTIVATED';
			}
			
			if($result->failed_logins > 3)
			{				
				$now = time();
				$wait = $now - 20;
				
				if($result->last_failure > $wait)
				{
					return 'TIMEOUT';
				}
			}
			
			if($result->change_password != '0')
			{
				// Redirect to change password form
				$key = $this->CI->session->flashdata_key;
				$this->CI->session->set_flashdata('msg', 'Please change your password.');
				$this->CI->session->set_userdata($key.':old:referrer', 'member/profile/edit');				
			}
			
			$password = sha1($this->salt.$result->hash.$password); // Hash input password
						
			if ($password === $result->password) // Passwords match?
			{
				$this->CI->session->set_userdata(array('id'=> $result->id));
				$this->CI->session->set_userdata(array('role_id'=> $result->role_id));
				//$this->CI->session->set_userdata(array('type'=> $result->type));
				$this->users_model->reset_failures($result->id);
				return TRUE;
			}
			else
			{
				$this->users_model->increment_failures($result->id, $result->failed_logins);
			}
		}
		
		return FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Logged In
	 *
	 * Checks to see if a visitor is logged into the site
	 *
	 * @access	public
	 * @param	void
	 * @return	bool
	 */
	function logged_in ()
	{
		return $var = ($this->CI->session->userdata('id')) ? TRUE : FALSE; 
		
	}

	// --------------------------------------------------------------------

	/**
	 * Logout
	 *
	 * Destroys the user's session
	 *
	 * @access	public
	 * @return	void
	 */
	function logout ()
	{
		$this->CI->session->unset_userdata('id');
		$this->CI->session->sess_destroy();		
	}

	// --------------------------------------------------------------------

	/**
	 * Activate
	 *
	 * Finds matching activation code and activates user
	 *
	 * @access	public
	 * @param	string activation_code
	 * @return	bool
	 */
	function activate ($activation_code)
	{
		$activate = $this->users_model->activate($activation_code);
	
		return $var = ($activate) ? TRUE : FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Forgotten Begin
	 *
	 * Starts the forgotten password procedure
	 *
	 * @access	public
	 * @param	string email
	 * @return	void
	 */
	function forgotten_password($email)
	{
		$CI =& get_instance();
		
		if($this->check_email($email))
		{
			$CI->load->library('email');
			$CI->email->initialize($this->mail);
			
			/* Generate new password. */
			$password = substr(sha1(microtime()), 0, 10);
			$this->users_model->update_password($password, $email, TRUE);

			$data['msg_view']	= 'forgot';
			$data['password']	= $password;
			
			$message = $CI->load->view('email/template', $data, TRUE);
			
			$CI->email->from($this->mail_from_email, $this->mail_from_name);
			$CI->email->to($email);
			$CI->email->subject($this->new_password_subject);	
			$CI->email->message($message);
			$CI->email->send();
			
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}

	// --------------------------------------------------------------------

	/**
	 * Get Group
	 *
	 * @access	public
	 * @return	mixed
	 */
	function get_group($id)
	{
		return $this->users_model->get_group($id);
	}

	// --------------------------------------------------------------------

	/**
	 * Check Username availability
	 *
	 * @access	public
	 * @param	string	username
	 * @return	bool
	 */
	function check_username($username)
	{
		return $this->users_model->check_unique('username', $username);
	}
	
	function check_chinhhang($type)
	{
		
		return $this->users_model->check_ch('type', $type);
	}

	// --------------------------------------------------------------------
	
	/**
	 * Check Email availability
	 *
	 * @access	public
	 * @param	string	email
	 * @return	bool
	 */
	function check_email($email)
	{
		return $this->users_model->check_unique('email', $email);
	}
	
	// --------------------------------------------------------------------
	
	/**
	 * Returns User Object
	 *
	 * @access	public
	 * @return	object	user object
	 */
	function get_user()
	{		
		if ( ! $this->logged_in())
		{
			$user			= new stdClass;
			$user->id		= -1;
			$user->is_admin	= FALSE;
			$user->role_id	= FALSE;
			
		}
		else
		{
			$user = $this->CI->users_model->get_user($this->CI->session->userdata('id'));
			$user->id = $user->user_id;
			$user->date_created = strtotime($user->date_created . " GMT");	// unix timestamp
			$user->is_admin = ($user->role_name	=== 'Admin') ? TRUE : FALSE;//group user
			$user->is_manager = ($user->role_name === 'Manager') ? TRUE : FALSE;
			$user->is_sitemanager = ($user->role_name === 'SiteManager') ? TRUE : FALSE;
			$user->is_teacher = ($user->role_name === 'Teacher') ? TRUE : FALSE;
			$user->is_tuyensinh = ($user->role_name === 'Tuyensinh') ? TRUE : FALSE;
			$user->is_ketoan = ($user->role_name === 'Ketoan') ? TRUE : FALSE;
			$user->is_vattu = ($user->role_name === 'Vattu') ? TRUE : FALSE;
			$user->confirm_logout = $this->CI->config->item('logout_confirmation');
		}
		
		return $user;
	}

	// --------------------------------------------------------------------

	/**
	 * Protect a controller / function
	 *
	 * @access	public
	 * @param	string	user group
	 */
	function restricts($user_group = FALSE)
	{
		if($user_group == 'logged_out')
		{
			if ($this->logged_in())
			{
				redirect('/member/users');
			}
		}
		else if( !$this->logged_in())
		{
			$this->CI->session->set_flashdata('referrer', $this->CI->uri->uri_string());
			redirect('/member/users/login');
		}
		else if ($user_group AND $this->CI->user->user_group !== $user_group)
		{
			$this->CI->session->set_flashdata('referrer', $this->CI->uri->uri_string());
			redirect('/member/users/login');
		}
	}
	
	public function role_id()
	{
			$this->user = $this->get_user();
			return $rol = $this->user->role_id;
	}//end role_id()
	
	public function restrict($permission=NULL, $uri=NULL)
	{
		$this->CI->session->set_userdata('previous_page', current_url());
		if( !$this->logged_in())
		{
			$this->CI->session->set_flashdata('referrer', $this->CI->uri->uri_string());
			redirect('/member/users/login');
		}
		$user_group = FALSE;
		// If user isn't logged in, don't need to check permissions
		//var_dump($this->logged_in()); exit();
		//echo $uri; exit();
		//echo $permission;
		//echo $this->role_id();
		//echo 'manh';
		if($user_group == 'logged_out')
		{
			redirect('/member/users/login');
		}
		/*if($this->has_permission($permission))
		{
			echo 'TRUE';
		}
		else
		{
			echo 'FALSE';
		}*/
		//
		// Check to see if the user has the proper permissions
		if (!empty($permission) && !$this->has_permission($permission))
		{
			// set message telling them no permission THEN redirect
			//Template::set_message( lang('us_no_permission'), 'attention');
			//echo 'a'; exit();
			if ($uri)
			{
				//echo 'a'; exit();
				redirect($uri);
			}
			else
			{
				//echo 'b'.$this->CI->session->userdata('previous_page'); exit();
				//redirect($this->CI->session->userdata('previous_page'));
				//echo 'ban ko du quyen'; 
				//redirect('javascript:history.go(-1)');
				//echo '
				//<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>'.'
				//Bạn không đủ quyền truy cập vui lòng bâm vào <a href="javascript:history.go(-1)"><strong>đây</strong></a> để quay lại trang trước';
				redirect($uri);
				//exit();
			}
		}

		return TRUE;

	}
	
	public function has_permission($permission = NULL, $role_id=NULL, $override = FALSE)
	{
		if (empty($permission))
		{
			return FALSE;
		}
		// move permission to lowercase for easier checking.
		else
		{
			$permission = strtolower($permission);
			//echo $permission;
		}

		// If no role is being provided, assume it's for the current
		// logged in user.
		if(empty($role_id))
		{
			$role_id = $this->role_id();
			//echo $role_id;
		}

		if (empty($this->perms)) {
			
			$this->load_permissions($role_id);
		}

		$perms = (object)$this->perms;
		//var_dump($this->perms);
		// Did we pass?
		if ((isset($perms->$permission) && $perms->$permission == 1) || (!in_array($permission, $this->perm_desc) && $override))
		{
			return TRUE;
		}

		return FALSE;

	}//end has_permission()
	
	public function load_permissions($role_id=NULL)
	{
		if (!class_exists('Permissions_model'))
		{
			$this->CI->load->module_model('member', 'permission_model', 'permission_model');
		}

		$perms_all = $this->CI->permission_model->find_status_by('status','active');
		$perms = array();
		foreach($perms_all as $key => $perm_details)
		{
			$perms[$perm_details['permission_id']] = $perm_details['name'];
		}

		$this->perm_desc = $perms;

		$role_id = !is_null($role_id) ? $role_id : $this->role_id();
		$role_perms = $this->CI->permission_model->find_for_role($role_id);
	
		if (is_array($role_perms))
		{
			foreach($role_perms as $key => $permission)
			{
				
				$this->perms[strtolower($perms[$permission['permission_id']])] = 1;
				//echo $this->perms[strtolower($perms[$permission['permission_id']])] ; exit();
			}
		}

	}//end load_permissions()
	
}

/* End of file Access.php */
/* Location: ./application/libraries/Access.php */